<?php
/**
 * PHP 大图生成小图(缩略图程序)
 *  可用于网站缩略图的显示
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-4-11
 * Time: 下午3:21
 */

function big_to_small_img($file,$path,$width = 120,$height = 90){
    $img = $path.$file;
    $imgarr = getimagesize($img);
    $s_w = $imgarr[0];//原图宽
    $s_h = $imgarr[1];//原图高
    $s_type = $imgarr[2];//原图类型 1 GIF 2 JPG 3 PNG

    //按比例缩放
    if($s_w/$s_h > $width/$height){
        $m_w = $width;
        $m_h = (int)$s_h * ($width/$s_w);
    }else{
        $m_w = (int)$s_w * ($height/$s_h);
        $m_h = $height;
    }
    //根据上传好的图形文件类型新建一个用来生成缩略图的源文件
    switch($s_type){
        case 1:
            $srcf = imagecreatefromgif($img);
            break;
        case 2:
            $srcf = imagecreatefromjpeg($img);
            break;
        case 3:
            $srcf = imagecreatefrompng($img);
            break;
        default:
            showmsg('Program call error');
            break;
    }


    //...
    $desf = imagecreatetruecolor($m_w,$m_h);
    imagecolorallocate($desf,255,255,255);
    imagecopyresampled($desf,$srcf, 0, 0, 0, 0, $m_w,$m_h,$s_w,$s_h);
    $sm_name = $path.'s_'.$file;
    switch($s_type){
        case 1:
            imagegif($desf,$sm_name);break;
        case 2:
            imagejpeg($desf,$sm_name);break;
        case 3:
            imagepng($desf,$sm_name);break;
        default:
            showmsg('Unable to generate thumbnails');
            break;
    }

    //释放图像资源
    imagedestroy($desf);
    imagedestroy($srcf);
    return $sm_name;
}




$file = 'test.jpg';
$path = './';
$name = big_to_small_img($file,$path,120,180);
echo 'Image Path :',$name;